package com.qk.pckeyspringboot.server;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;

@Service
public class JsonFileService {
    @Value("${app.json.file-path}")
    private String path;
    /**
     * 检查文件是否存在
     * @param filePath 文件路径
     * @return 如果文件存在返回true，否则返回false
     */
    public static boolean isFileExists(String filePath) {
        File file = new File(filePath);
        return file.exists() && file.isFile();
    }

    public String readJsonFile() {
        if (!isFileExists(path)){
            return "文件不存在";
        }
        File file = new File(path);
        try {
            return FileUtils.readFileToString(file, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return "未知错误";
        }
    }

    public String writeJsonFile(String json){
        File file = new File(path);
        try {
            FileUtils.writeStringToFile(file, json, "UTF-8");
            return "写入成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "未知错误";
        }
    }
}
